package com.wangsh.splider.web.back.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.wangsh.splider.common.pojo.ApiResponse;
import com.wangsh.splider.common.pojo.ApiResponseEnum;
import com.wangsh.splider.common.util.ConstatFinalUtil;
import com.wangsh.splider.common.util.PageInfoUtil;
import com.wangsh.splider.controller.BaseController;
import com.wangsh.splider.orders.pojo.AOrdersClient;
import com.wangsh.splider.orders.pojo.AOrdersUsers;
import com.wangsh.splider.orders.service.IOrdersOperService;
import com.wangsh.splider.orders.service.IOrdersDbService;
import com.wangsh.splider.system.pojo.ASysCountry;
import com.wangsh.splider.system.pojo.ASysCountryEnum;
import com.wangsh.splider.system.pojo.ASysIp;
import com.wangsh.splider.system.service.ISystemOperService;
import com.wangsh.splider.system.service.ISystemDbService;

/**
 * 	系统后台操作
 * 	@author wangsh
 */
@Controller
@RequestMapping("/back/orders/")
public class OrdersBackController extends BaseController
{
	@Resource
	private IOrdersDbService ordersDbService;
	@Resource
	private IOrdersOperService ordersOperService;
	@Resource
	private ISystemOperService systemOperService;
	@Resource
	private ISystemDbService systemDbService;
	
	/* ==== 订单客户端请求管理开始 ==== */
	/**
	 * 订单客户端请求管理页面
	 * 
	 * @return
	 */
	@RequestMapping("/clientList")
	public String clientList(HttpServletRequest request, Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--clientList--");
		/* 分页信息 */
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(request);
		/* 搜索条件,生成公共的搜索条件 */
		Map<String, Object> condMap = this.proccedSearch(request);
		
		/* 添加搜索条件 */
		String souType = request.getParameter("souType");
		request.setAttribute("souType", souType);
		condMap.put("souType", souType);
		/*
		 * 查询数据库 所有的数据以JSON的形式返回
		 */
		ApiResponse<AOrdersClient> response = this.ordersDbService.findCondListClientService(pageInfoUtil, condMap);
		/* 将结果存储到Request中 */
		model.addAttribute("response", response.toJSON());
		return "/back/orders/clientList";
	}

	/**
	 * 打开更新订单客户端请求管理页面
	 * 
	 * @return
	 */
	@RequestMapping("/clientUpdate")
	public String clientUpdate(String id, String operType, Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--clientUpdate--");
		/* 准备查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", id);
		/* 查询数据库 */
		ApiResponse<AOrdersClient> response = this.ordersDbService.findOneClientService(condMap);
		/* 存储request */
		model.addAttribute("response", response.toJSON());

		if ("update".equalsIgnoreCase(operType))
		{
			return "/back/orders/clientUpdate";
		}else if ("html".equalsIgnoreCase(operType))
		{
			return "/back/orders/clientHtml";
		}
		return "/back/orders/clientInfo";
	}

	/**
	 * 添加订单客户端请求管理提交操作
	 * 
	 * @return
	 */
	@RequestMapping(value = "/clientUpdateSubmit", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String clientUpdateSubmit(String id, HttpServletRequest request, Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--clientUpdateSubmit--");
		/* 准备查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", id);
		/* 查询数据库 */
		ApiResponse<AOrdersClient> response = this.ordersDbService.findOneClientService(condMap);
		/* 获取java对象 */
		AOrdersClient ordersClient = response.getDataOneJava();

		/* 接收参数 */
		String pubTimeStr = request.getParameter("pubTimeStr");
		ordersClient.setPubTime(this.dateFormatUtil.strDateTime(pubTimeStr));
		
		String status = request.getParameter("status");
		String ip = request.getParameter("ip");
		String cookieClient = request.getParameter("cookieClient");
		String cookieTarget = request.getParameter("cookieTarget");
		String content = request.getParameter("content");
		String souType = request.getParameter("souType");
		
		/* 先存储Ip地址 */
		ApiResponse<ASysIp> sysIpApiResponse = this.systemOperService.operFindIp(ip);
		ASysIp sysIp = sysIpApiResponse.getDataOneJava() ;
		
		/* 设置属性 */
		ordersClient.setStatus(Byte.valueOf(status));
		ordersClient.setSysIpId(sysIp.getId());
		ordersClient.setCookieClient(cookieClient);
		ordersClient.setCookieTarget(cookieTarget);
		ordersClient.setContent(content);
		ordersClient.setSouType(Byte.valueOf(souType));
		
		// 更新时间不用获取
		ordersClient.setUpdateTime(new Date());
		/* 数据库操作 */
		ApiResponse dbRes = ordersDbService.updateOneClientService(ordersClient);

		ConstatFinalUtil.SYS_LOGGER.info("--订单客户端请求管理添加返回结果:{}--", dbRes.toJSON());
		return dbRes.toJSON().toJSONString();
	}
	/* ==== 订单客户端请求管理结束 ==== */
	
	/* ==== 订单用户请求管理开始 ==== */
	/**
	 * 订单用户请求管理页面
	 * 
	 * @return
	 */
	@RequestMapping("/usersList")
	public String usersList(HttpServletRequest request, Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--usersList--");
		/* 搜索条件 */
		String ordersUsersId =request.getParameter("ordersUsersId");
		String clientId = request.getParameter("clientId");
		if(clientId == null)
		{
			clientId = "" ; 
		}
		request.setAttribute("clientId", clientId);
		request.setAttribute("ordersUsersId", ordersUsersId);
		String souType = request.getParameter("souType");
		if(souType == null)
		{
			souType = "" ; 
		}
		request.setAttribute("souType", souType);
		/* 分页信息 */
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(request);
		/* 搜索条件,生成公共的搜索条件 */
		Map<String, Object> condMap = this.proccedSearch(request);
		/* 放置额外的搜索条件 */
		condMap.put("clientId", clientId);
		condMap.put("ordersUsersId", ordersUsersId);
		condMap.put("souType", souType);
		/* ====增加搜索条件开始==== */
		String orderBy = request.getParameter("orderBy");
		if(orderBy == null)
		{
			orderBy = "" ; 
		}
		request.setAttribute("orderBy", orderBy);
		condMap.put("orderBy", orderBy);
		/* ====增加搜索条件结束==== */
		
		/* =====搜索条件国家开始===== */
		String countryId = request.getParameter("countryId");
		if(countryId == null)
		{
			countryId = "" ; 
		}
		request.setAttribute("countryId", countryId);
		condMap.put("countryId", countryId);
		/* =====搜索条件国家结束===== */
		
		/*
		 * 查询数据库 所有的数据以JSON的形式返回
		 */
		ApiResponse<AOrdersUsers> response = this.ordersDbService.findCondListUsersService(pageInfoUtil, condMap);
		/* 将结果存储到Request中 */
		model.addAttribute("response", response.toJSON());
		/* 查询所有启用的国家 */
		condMap.clear();
		condMap.put("status", ASysCountryEnum.STATUS_ENABLE.getStatus());
		ApiResponse<ASysCountry> apiResponseCountry = this.systemDbService.findCondListCountryService(null, condMap);
		model.addAttribute("countryResponse", apiResponseCountry.toJSON());
		return "/back/orders/usersList";
	}

	/**
	 * 打开更新订单用户请求管理页面
	 * 
	 * @return
	 */
	@RequestMapping("/usersUpdate")
	public String usersUpdate(String id, String operType, Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--usersUpdate--");
		/* 准备查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", id);
		/* 查询数据库 */
		ApiResponse<AOrdersUsers> response = this.ordersDbService.findOneUsersService(condMap);
		/* 存储request */
		model.addAttribute("response", response.toJSON());

		if ("update".equalsIgnoreCase(operType))
		{
			return "/back/orders/usersUpdate";
		}else if ("html".equalsIgnoreCase(operType))
		{
			return "/back/orders/usersHtml";
		}
		return "/back/orders/usersInfo";
	}

	/**
	 * 添加订单用户请求管理提交操作
	 * 
	 * @return
	 */
	@RequestMapping(value = "/usersUpdateSubmit", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String usersUpdateSubmit(String id, HttpServletRequest request, Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--usersUpdateSubmit--");
		/* 准备查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", id);
		/* 查询数据库 */
		ApiResponse<AOrdersUsers> response = this.ordersDbService.findOneUsersService(condMap);
		/* 获取java对象 */
		AOrdersUsers ordersUsers = response.getDataOneJava();

		/* 接收参数 */
		String pubTimeStr = request.getParameter("pubTimeStr");
		ordersUsers.setPubTime(this.dateFormatUtil.strDateTime(pubTimeStr));
		
		String status = request.getParameter("status");
		String content = request.getParameter("content");
		/* 设置属性 */
		ordersUsers.setStatus(Byte.valueOf(status));
		ordersUsers.setContent(content);
		
		// 更新时间不用获取
		ordersUsers.setUpdateTime(new Date());
		/* 数据库操作 */
		ApiResponse dbRes = ordersDbService.updateOneUsersService(ordersUsers);

		ConstatFinalUtil.SYS_LOGGER.info("--订单用户请求管理添加返回结果:{}--", dbRes.toJSON());
		return dbRes.toJSON().toJSONString();
	}
	
	/**
	 * 订单用户批量操作
	 * @return
	 */
	@RequestMapping(value = "/usersBatch" , produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String usersBatch(HttpServletRequest request,Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--usersBatch--");
		Map<String, Object> condMap = new HashMap<String, Object>();
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		/* 从session中获取信息 */
		String[] ids = request.getParameterValues("ids");
		
		/* 操作类型 */
		String operType = request.getParameter("operType");
		if(ids != null)
		{
			int totalNum = ids.length ; 
			int succedNum = 0 ; 
			int failedNum = 0 ; 
			for (int i = 0; i < ids.length; i++)
			{
				String id = ids[i];
				condMap.clear();
				condMap.put("id", id);
				ApiResponse<AOrdersUsers> apiResponseDb = this.ordersDbService.findOneUsersService(condMap);
				AOrdersUsers users = apiResponseDb.getDataOneJava();
				
				boolean updateFlag = false ;
				if("status".equalsIgnoreCase(operType))
				{
					String status = request.getParameter("status");
					
					/* 设置状态 */
					users.setStatus(Byte.valueOf(status));
					updateFlag = true ; 
				}else if("souType".equalsIgnoreCase(operType))
				{
					String souType = request.getParameter("souType");
					
					/* 设置状态 */
					users.setSouType(Byte.valueOf(souType));
					updateFlag = true ; 
				}else if("fbTarget".equalsIgnoreCase(operType))
				{
					/* 批量更新用户的Cookie */
					apiResponse = this.ordersOperService.updateRequestHeadTargetService(users);
					
					if(apiResponse.getCode() == ApiResponseEnum.STATUS_SUCCESS.getStatus())
					{
						succedNum ++ ; 
					}else
					{
						failedNum ++ ; 
					}
					updateFlag = false ; 
				}
				
				if(updateFlag)
				{
					users.setPubTime(new Date());
					apiResponse = this.ordersDbService.updateOneUsersService(users);
					if(apiResponse.getCode() == ApiResponseEnum.STATUS_SUCCESS.getStatus())
					{
						succedNum ++ ; 
					}else
					{
						failedNum ++ ; 
					}
				}
			}
			
			StringBuffer sb = new StringBuffer();
			sb.append("总条数:" + totalNum + ";");
			sb.append("成功条数:" + succedNum + ";");
			sb.append("失败条数:" + failedNum + ";");
			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
			apiResponse.setInfo(sb.toString(), Collections.EMPTY_MAP);
		}
		return apiResponse.toJSON().toJSONString();
	}
	
	/**
	 * excel文件的上传
	 */
	@RequestMapping(value = "/excelUpload", method = RequestMethod.POST)
	public String fileUpload(@RequestParam("excel")MultipartFile file)
	{
		OutputStream os = null;
		InputStream is = null;
		try
		{
			String fileName = "";
			String truePath = "";
			String trueFileName = "";
			ConstatFinalUtil.SYS_LOGGER.info("文件名:{},文件大小:{},表单名:{}", file.getOriginalFilename(), file.getSize(),
					file.getName());
			fileName = file.getOriginalFilename();
			// 截取源文件的文件名后缀
			String fileNameSuffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
			if ("xls".equals(fileNameSuffix) || "xlsx".equals(fileNameSuffix))
			{
				InputStream inputStream = file.getInputStream();
				UUID randomUUID = UUID.randomUUID();
				JSONObject jo = (JSONObject) ConstatFinalUtil.SYS_JSON.get("config");
				truePath = jo.getString("excel.truePath") + "/excel";
				trueFileName = randomUUID + "." + fileNameSuffix;
				String path = truePath + "/" + trueFileName;
				File excel = new File(path);
				if (!excel.exists())
				{
					if (!excel.getParentFile().exists())
					{
						excel.getParentFile().mkdirs();
					}
				}
				excel.createNewFile();
				os = new FileOutputStream(excel);
				boolean copyFile = this.fileUtil.copyFile(inputStream, os);
				// file.transferTo(file);
				if (copyFile)
				{
					is = new FileInputStream(excel);
					this.poiUtil.readExcel(is,"");
					//this.ordersOperServiceImpl.readXls(path);
				
				}else {
					//提示 保存文件失败
				}
			} else
			{
				//提示文件格式不对
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		return "redirect:/back/orders/usersList";

	}	
	
	/**
	  * 打开上传文件页面
	 * @return
	 */
	@RequestMapping("/usersInsert")
	public String usersIpInsert()
	{
		ConstatFinalUtil.SYS_LOGGER.info("--usersInsert--");
		return "/back/orders/usersInsert";
	}
	
	@RequestMapping(value = "/usersInsertSubmit",produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String usersInsertSubmit()
	{
		ConstatFinalUtil.SYS_LOGGER.info("--usersInsertSubmit--");
		return info;
	}

	
	/* ==== 订单用户请求管理结束 ==== */
}